<script setup>
import { ref } from 'vue';
import axios from 'axios';
import config from '../../config.js';
import { useRouter } from 'vue-router';

// 文件引用
const fileInput = ref(null);
// 上传状态
const uploading = ref(false);
// 上传结果
const result = ref('');
// 错误信息
const error = ref('');
const router = useRouter();

// 处理文件上传
const handleFileUpload = async () => {
  if (!fileInput.value || !fileInput.value.files.length) {
    error.value = '请选择一个CSV文件';
    return;
  }

  const file = fileInput.value.files[0];
  if (file.type !== 'text/csv' && !file.name.endsWith('.csv')) {
    error.value = '请上传CSV格式的文件';
    return;
  }

  uploading.value = true;
  error.value = '';
  result.value = '';

  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await axios.post(
      `${config.api.baseUrl}/api/stocks/import`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    );

    result.value = `导入成功：${response.data.successCount} 条记录成功，${response.data.failCount} 条记录失败`;
    console.log('导入结果:', response.data);
  } catch (err) {
    error.value = '导入失败: ' + (err.response?.data?.error || err.message);
    console.error('导入失败:', err);
  } finally {
    uploading.value = false;
  }
};

// 返回股票列表
const goToStockList = () => {
  router.push('/stocks');
};
</script>

<template>
  <div class="stock-import-container">
    <h1>导入股票CSV</h1>

    <div class="import-form">
      <div class="form-group">
        <label for="file-upload">选择CSV文件：</label>
        <input
          type="file"
          id="file-upload"
          ref="fileInput"
          accept=".csv"
          :disabled="uploading"
        />
        <p class="help-text">CSV文件必须包含股票名称和代码两个字段（无需表头）</p>
      </div>

      <div class="action-buttons">
        <button @click="handleFileUpload" :disabled="uploading">
          {{ uploading ? '导入中...' : '开始导入' }}
        </button>
        <button @click="goToStockList" :disabled="uploading">返回列表</button>
      </div>
    </div>

    <div v-if="error" class="error-message">{{ error }}</div>
    <div v-if="result" class="success-message">{{ result }}</div>

    <div v-if="uploading" class="loading-indicator">
      <div class="spinner"></div>
      <span>正在导入...</span>
    </div>
  </div>
</template>

<style scoped>
.stock-import-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  color: #333;
  border-bottom: 2px solid #42b983;
  padding-bottom: 10px;
}

.import-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 5px;
  margin-top: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input[type="file"] {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 100%;
}

.help-text {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

button {
  padding: 8px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:hover:not(:disabled) {
  background-color: #3aa876;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.error-message {
  color: #e74c3c;
  background-color: #fadbd8;
  padding: 10px;
  border-radius: 4px;
  margin-top: 20px;
}

.success-message {
  color: #2ecc71;
  background-color: #d5f5e3;
  padding: 10px;
  border-radius: 4px;
  margin-top: 20px;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-left-color: #42b983;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>